import { PageContainer, ProTable, ModalForm, ProFormText,
  ProFormSelect, ProDescriptions,FooterToolbar } from '@ant-design/pro-components';
import { user, addUser, updateUser,removeUser } from '@/services/ant-design-pro/api';
import { Button, message, Drawer } from 'antd';
import { useState, useRef, useEffect } from 'react';
import UpdateForm from './components/UpdateForm';
async function handleAdd(fields) {
  //显示loading效果,返回一个隐藏loading效果的方法
  const hide = message.loading('正在添加用户...');
  try {
    await addUser(fields);
    message.success('新建用户成功');
    return true;
  } catch (error) {
    message.error('新建用户失败');
    return false;
  } finally {
    hide();
  }
}
async function handleUpdate(fields) {
  //显示loading效果,返回一个隐藏loading效果的方法
  const hide = message.loading('正在添加用户...');
  try {
    await updateUser(fields);
    message.success('更新用户成功');
    return true;
  } catch (error) {
    message.error('更新用户失败');
    return false;
  } finally {
    hide();
  }
}
//handleRemove
async function handleRemove(selectedRows) {
  //显示loading效果,返回一个隐藏loading效果的方法
  const hide = message.loading('正在删除用户...');
  try {
    await removeUser({userid:selectedRows.map(row=>row.userid)});
    message.success('删除用户成功');
    return true;
  } catch (error) {
    message.error('删除用户失败');
    return false;
  } finally {
    hide();
  }
}
const UserList = () => {
  let [createModalOpen, setCreateModalOpen] = useState(false);
  let [currentRow, setCurrentRow] = useState(null);
  let [showDetail, setShowDetail] = useState(false);
  let [updateModalOpen, setUpdateModalOpen] = useState(false);
  let [selectedRows,setSelectedRows] = useState([]);
  const restFormRef = useRef(null);
  const actionRef = useRef(null);
  const detailRef = useRef(null);

  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      valueType: 'text',
      tip: '用户名必须是唯一的',
      render: (value, record) => {
        return (
          <a onClick={() => {
            setCurrentRow(record);//设置当前行
            setShowDetail(true);
          }}>
            {value}
          </a>
        )
      }
    },
    {
      title: '姓名',
      dataIndex: 'name',
      sorter:true,
      valueType: 'text'
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      valueType: 'text'
    },
    {
      title: '角色',
      dataIndex: 'access',
      valueType: 'select',
      sorter:true,//支持排序
      filters:true,//支持过滤
      valueEnum: {
        'root': {
          text: '超级管理员',
        },
        'admin': {
          text: '管理员',
        },
        'user': {
          text: '普通会员',
        }
      }
    },
    {
      title: '操作',
      render: (_, record) => {
        return (
          <a key="update" onClick={() => {
            setCurrentRow(record);//设置当前正在编辑的对象为record
            setUpdateModalOpen(true);//打开更新模态窗口
          }}>更新</a>
        )
      }
    }
  ]
  const handleCreateModal = () => {
    //重置表单的值
    restFormRef.current?.resetFields();
    setCreateModalOpen(true)
  }
  useEffect(()=>{
    detailRef.current?.reload();
  },[currentRow]);
  return (
    <PageContainer>
      <ProTable
        headerTitle="用户管理"
        columns={columns}
        request={user}
        rowKey="userid"
        toolBarRender={
          () => [
            <Button type="primary" key="primary"
              onClick={handleCreateModal}>新建用户</Button>
          ]
        }
        actionRef={actionRef}
        rowSelection={{
          onChange:(_,selectedRows)=>{
            setSelectedRows(selectedRows);
          }
        }}
      />
      {
        selectedRows.length>0&&(
          <FooterToolbar
            extra={
              <div>
                已选中{selectedRows.length}项
              </div>
            }

          >
            <Button danger onClick={async ()=>{
              await handleRemove(selectedRows);
              setSelectedRows([]);
              actionRef.current.reloadAndRest();
            }}>
              批量删除
            </Button>
            </FooterToolbar>
        )
      }
      <ModalForm
        title="新建用户"
        width="400px"
        open={createModalOpen}
        modalProps={{ destroyOnClose: true }}
        formRef={restFormRef}
        onOpenChange={setCreateModalOpen}
        onFinish={async (values) => {
          //调用接口添加用户
          let success = await handleAdd(values);
          //如果返回true说明成功了，如果成功了则重新刷新当前页的数据
          if (success) {
            setCreateModalOpen(false);
            actionRef.current.reload();
          }
        }}
      >
        <ProFormText
          width="md"
          name="username"
          label="用户名"
          rules={[{ required: true, message: '用户名为必填项' }]}
        />
        <ProFormText
          width="md"
          name="password"
          label="密码"
          rules={[{ required: true, message: '密码为必填项' }]}
        />
        <ProFormText
          width="md"
          name="name"
          label="姓名"
          rules={[{ required: true, message: '姓名为必填项' }]}
        />
        <ProFormText
          width="md"
          name="email"
          label="邮箱"
          rules={[{ required: true, message: '邮箱为必填项' }]}
        />
        <ProFormSelect
          name="access"
          label="角色"
          width="md"
          rules={[{ required: true, message: '角色为必填项' }]}
          options={
            [
              { value: 'root', label: '超级管理员' },
              { value: 'admin', label: '管理员' },
              { value: 'user', label: '普通会员' }
            ]
          }
        />
      </ModalForm>
      <UpdateForm
        onSubmit={async (values) => {
          console.log('UpdateForm values', values)
          let newUser = { ...values, userid: currentRow.userid };
          let success = await handleUpdate(newUser);
          if (success) {
            actionRef.current.reload();
            if(showDetail){
              setCurrentRow(newUser);
            }else{
              setCurrentRow(undefined);
            }
            setUpdateModalOpen(false);
          }
        }}
        onCancel={() => {
          setUpdateModalOpen(false);
        }}
        updateModalOpen={updateModalOpen}
        values={currentRow || {}}
      />
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {
          currentRow && (
            <ProDescriptions
              column={2}
              title={currentRow.name}
              request={async ()=>({data:currentRow||{}})}
              columns={columns}
              actionRef={detailRef}
            ></ProDescriptions>)
        }
      </Drawer>
    </PageContainer>
  )
}

export default UserList;
